<?php
namespace app\backend\model;

use think\Model;

class Auth extends Model {
    use FormDateTrait;
    protected $autoWriteTimestamp = true;//自动时间戳
    protected $createTime = 'regtime';
    protected $updateTime = false;
	 protected $table = 'adm';
	//多对多关联 角色-用户
	public function role()
    {
        return $this->belongsToMany('AuthRole','auth_role_adm','role_id','adm_id');
    }
    public function getStatusAttr($value)
    {
        $status = config('status.locked');
        return $status[$value];
    }
    public function getList(){
    	return self::with('role')->paginate(2);
//    	return self::with('role')->paginate(config('num_each_page'));
    }
    //关联新增
    public function relationAdd($id,$roles){
        $user = self::get($id);
        $res = $user->role()->saveAll($roles);
//        halt($res);
        return $res;
    }
    //通过uid获取node列表
    public static function getAuthNodes($admin_id){
	    if($nodes = session(config('status.auth.user_auth_nodes'))) return $nodes;

        //获取用户的管理组角色id
        $user = self::get($admin_id, 'role');
        $roles = $user->role;
        if($roles==false) return 'norole';
        foreach ($roles as $role) {
            $r_ids[] = $role->id; // 获得角色id
        }
        //获取角色的节点
        $nodes = AuthRole::selectNodes($r_ids);
        if($nodes == false) return 'nonode';

        session(config('status.auth.user_auth_nodes'),$nodes); //把节点放到session里
        return $nodes;
    }
    public static function makeFromData($default_value = [])
    {
        $data = [
            [
                'type' => 'input',
                'name' => 'account',
                'label' => '名称',
                'verify' => 'name'
            ],
            [
                'type' => 'password',
                'name' => 'password',
                'label' => '密码',
                'verify' => 'password'
            ],
            [
                'type' => 'checkbox',
                'name' => 'role_id',
                'label' => '管理组',
                'options' => AuthRole::where('status',1)->column('name','id')
            ],
            [
                'type' => 'radio',
                'name' => 'status',
                'label' => '状态',
                'options' => config('status.active'),
            ],
        ];
        return self::mergeDefaultFormData($data, $default_value);
    }
}